﻿using System;
using System.Text;
using System.IO;

class RC4Utilities
{
    static void Main()
    {
        string inputFile = @"..\..\RC4Utilities.cs";
        string password = "taina";
        string outputFile = @"..\..\RC4Utilities.encr";
        RC4FileEncript(inputFile, password, outputFile);
    }

    private static void RC4FileEncript(string inputFile, string password, string outputFile)
    {
        using (FileStream fs = new FileStream(inputFile, FileMode.Open))
        {
            byte[] array = new byte[fs.Length];
            fs.Read(array, 0, array.Length);
            RC4(ref array, Encoding.Unicode.GetBytes(password));
            using (FileStream fw = new FileStream(outputFile, FileMode.OpenOrCreate))
            {
                fw.Write(array, 0, array.Length);
            }
        }
    }

    static private void RC4(ref Byte[] bytes, Byte[] key)
    {
        Byte[] s = new Byte[256];
        Byte[] k = new Byte[256];
        Byte temp;
        int i, j;

        for (i = 0; i < 256; i++)
        {
            s[i] = (Byte)i;
            k[i] = key[i % key.GetLength(0)];
        }

        j = 0;
        for (i = 0; i < 256; i++)
        {
            j = (j + s[i] + k[i]) % 256;
            temp = s[i];
            s[i] = s[j];
            s[j] = temp;
        }

        i = j = 0;
        for (int x = 0; x < bytes.GetLength(0); x++)
        {
            i = (i + 1) % 256;
            j = (j + s[i]) % 256;
            temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            int t = (s[i] + s[j]) % 256;
            bytes[x] ^= s[t];
        }
    }
}
